package com.example.schoolguider.filter;

import com.alibaba.fastjson.JSON;
import com.example.schoolguider.model.User;
import com.example.schoolguider.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author wjc
 * @date 2022/7/2 18:18
 * 登录校验、权限赋予
 */
@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if((token==null||token=="")&&request.getRequestURI().contains("/activity/download")){
            try{
                token = request.getParameter("token");
            }catch (Exception ex){

            }
        }
        Enumeration<String> headers = request.getHeaderNames();
        if(token==null||token.isEmpty()||token==""||!(token.startsWith("Bearer ")||(token.startsWith("bearer ")))){
            filterChain.doFilter(request,response);
            return;
        }
        token = token.replace("Bearer ","").replace("bearer ","");
        User user;
        try {
            Claims claims = JWTUtil.parseJwt(token);
            user = JSON.parseObject(JSON.toJSONString(claims.get("user", LinkedHashMap.class)),User.class);
        }
        catch (Exception e){
            e.printStackTrace();
//            throw new RuntimeException("Token非法");
            filterChain.doFilter(request,response);
            return;
        }
        List<SimpleGrantedAuthority> auths = new ArrayList<>();
//        List<Role> roles = roleService.getRoles(user.getUserId());
//        for (Role role:
//             roles) {
//            auths.add(new SimpleGrantedAuthority((String)role.getRole()));
//        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(user,null,auths);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request,response);
    }
}
